import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import ElementUI, { TabPane } from 'element-ui';
import VueRouter from 'vue-router';
import Login from './components/Login.vue';
import Home from './components/Home.vue';
import User from './components/User.vue';
import Role from './components/Role.vue';
import 'element-ui/lib/theme-chalk/index.css';
import {Message} from 'element-ui';
import store from './store';
Vue.use(ElementUI);
Vue.use(VueRouter);
axios.defaults.withCredentials=true

axios.interceptors.response.use(response => {
  console.log("axios.interceptors.response.use(response => {}",response)
return response;
},error => {
// Do something with response error
console.info("------{}",error.response);
if(error.response.status==401){
  Message.error('尚未登录');
  router.replace({path:"/"});
}

return Promise.reject(error);
});

Vue.prototype.axios = axios;
Vue.prototype.requestUrl = "http://localhost:8081"
const routes= [
  {path:"/",component:Login},
  {path:"/home",component:Home,
  children:[
    {path:"/user",component:User},
    {path:"/role",component:Role}
  ]}
  
]

const router = new VueRouter({
  routes
})

//路由的钩子函数
router.beforeEach((to, from, next) => {
   console.log("要跳转的路径未：---->",to.path);
   if(to.path=='/'){
      store.commit('login',null);
      localStorage.removeItem('user');
      next();
   }else{
     //请求后台查询登录用户对应的菜单
     initMenu(router);
     setTimeout(() => {
       next();
     }, 100);
   }
})

 export const  initMenu =   (router)=>{
    axios({
    method:'get',
    url: "http://localhost:8081/menu/getMenuListByUsername"
  }).then(function(res){
         var arry = res.data.obj;
        var routers =  setRouter(arry);
        // console.log('routers-------------------->',routers);
        // console.log('router-------------------->',router);
        router.options.routes[1].children = routers;
        // console.log('router.options.routes--->',router.options.routes);
        router.addRoutes(router.options.routes);
        localStorage.setItem('router',JSON.stringify(routers));
        // console.log(' router.options.routes[1].children-------------------->', router.options.routes[1].children);
  })
}

export const setRouter=(routers)=>{
    var array = [];
    for(var i = 0;i<routers.length;i++){
      //递归
      var children = [];
      if(routers[i].children && routers[i].children instanceof Array){
        children = setRouter(routers[i].children);
      }
      var r = {
        path:routers[i].path,
        name:routers[i].name,
        children:children,
        component(resolve){
            require(['./components/'+component+".vue"],resolve)          
        }
      }
      array.push(r);
    }
    return array;

}

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
